package service

import (
	"bytes"
	"errors"
	"io"
	"k8s.io/apimachinery/pkg/util/json"
	"teresa/config"

	//"fmt"
	"context"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var Pod pod

type pod struct{}

type PodsResp struct {
	Total int          `json:"total"`
	Items []corev1.Pod `json:"items"`
}

func (p *pod) GetPodDetail(podName, namespace string) (pod *corev1.Pod, err error) {
	pod, err = K8s.ClientSet.CoreV1().Pods(namespace).Get(context.TODO(), podName, metav1.GetOptions{})
	if err != nil {
		logger.Error("获取失败," + err.Error())
		return nil, errors.New("获取失败," + err.Error())
	}

	return pod, nil
}

func (p *pod) DeletePod(podName, namespace string) (err error) {
	err = K8s.ClientSet.CoreV1().Pods(namespace).Delete(context.TODO(), podName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error("delete pod failed," + err.Error())
		return errors.New("delete pod failed,," + err.Error())
	}
	return nil
}

func (p *pod) UpdatePod(podName, namespace, content string) (err error) {
	var pod = &corev1.Pod{}
	//fan xu lie hua wei pod duixiang
	err = json.Unmarshal([]byte(content), pod)
	if err != nil {
		logger.Error("fan xu lie hua failed," + err.Error())
		return errors.New("fan xu lie hua failed," + err.Error())
	}
	_, err = K8s.ClientSet.CoreV1().Pods(namespace).Update(context.TODO(), pod, metav1.UpdateOptions{})
	if err != nil {
		logger.Error("delete pod failed," + err.Error())
		return errors.New("delete pod failed," + err.Error())
	}
	return nil
}

func (p *pod) GetPodContainer(podName, namespace string) (containers []string, err error) {
	pod, err := p.GetPodDetail(podName, namespace)
	if err != nil {
		return nil, err
	}
	for _, container := range pod.Spec.Containers {
		containers = append(containers, container.Name)
	}
	return containers, nil
}

func (p *pod) GetPodLog(containername, podName, namespace string) (log string, err error) {
	lineLimit := int64(config.PodLogTailLine)
	option := &corev1.PodLogOptions{
		Container: containername,
		TailLines: &lineLimit,
	}
	req := K8s.ClientSet.CoreV1().Pods(namespace).GetLogs(podName, option)
	podLogs, err := req.Stream(context.TODO())
	if err != nil {
		logger.Error(errors.New("获取podLog失败," + err.Error()))
		return "", errors.New("获取podLog失败," + err.Error())
	}
	defer podLogs.Close()
	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, podLogs)
	if err != nil {
		logger.Error(errors.New("转换podLog失败," + err.Error()))
		return "", errors.New("转换podLog失败," + err.Error())
	}
	return buf.String(), nil
}

type PodsNp struct {
	Namespace string
	PodNum    int
}

//func (p *pod)GetPodNumberNp()(data []corev1.Namespace,err error){
func (p *pod) GetPodNumberNp() (podsNps []*PodsNp, err error) {
	namespaceList, err := K8s.ClientSet.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error("获取所有namespace失败," + err.Error())
		return nil, errors.New("获取所有namespace失败," + err.Error())
	}
	for _, namespace := range namespaceList.Items {
		podList, err := K8s.ClientSet.CoreV1().Pods(namespace.Name).List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			return nil, err
		}
		podsNp := &PodsNp{
			Namespace: namespace.Name,
			PodNum:    len(podList.Items),
		}
		podsNps = append(podsNps, podsNp)
	}
	return podsNps, nil
}

//类型转换的方法corev1.Pod -->DataCell, DataCell ->corev1.Pod
func (p *pod) toCells(pods []corev1.Pod) []DataCell {
	cells := make([]DataCell, len(pods))
	for i := range pods {
		cells[i] = podCell(pods[i])
	}
	return cells
}

func (p *pod) fromCells(cells []DataCell) []corev1.Pod {
	pods := make([]corev1.Pod, len(cells))
	for i := range cells {
		//cells[i].(podCell)是将datacell类型转成podCell
		pods[i] = corev1.Pod(cells[i].(podCell))
	}
	return pods
}

//获取pod列表，支持过滤，排序，分页
func (p *pod) GetPods(filterName, namespace,deploymentName string, limit, page int) (podsResp *PodsResp, err error) {
	//context.TODO()用于声明一个空滤的context上下文，用于List方法内设置这个请求的超时
	// metav1.ListOptions{}用于过滤List数据，如使用label、field等
	//kc get pod --all-namespaces --filed-selector metadata.namespace != default

	// 获取pod的时候必须传入deployment的名字
	//var podList *corev1.PodList
	//if len(deploymentName) == 0 {
	//	podList, err = K8s.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
	//} else {
	//	label := "app="+deploymentName
	//	podList, err := K8s.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: label})
	//}

	label := "app="+deploymentName
	podList, err := K8s.ClientSet.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: label})
	if err != nil {
		//logger用于打印日志
		//return用于返回给前端，前端打印出来error
		logger.Info("获取pod列表失败," + err.Error())
		return nil, errors.New("获取pod列表失败," + err.Error())
	}
	selectableData := &dataSelector{
		GenericDataList: p.toCells(podList.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}

	filtered := selectableData.Filter()
	data := filtered.Sort().Paginate()

	total := len(data.GenericDataList) //后面发现最后return的时候，是在分页前的总行数，怪不得没有限制分页行数
	pods := p.fromCells(data.GenericDataList)
	return &PodsResp{
		Total: total,
		Items: pods,
	}, nil
}

func (p *pod) GetNodePods(filterName string, limit, page int) (podsResp *PodsResp, err error) {
	// kc get pod --all-namespaces --filed-selector spec.nodeName=node02

	podList1, err := K8s.ClientSet.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{
		FieldSelector: "spec.nodeName=node02",
	})
	if err != nil {
		//logger用于打印日志
		//return用于返回给前端，前端打印出来error
		logger.Info("获取pod列表失败," + err.Error())
		return nil, errors.New("获取pod列表失败," + err.Error())
	}
	selectableData1 := &dataSelector{
		GenericDataList: p.toCells(podList1.Items),
		DataSelect: &DataSelectQuery{
			Filter: &FilterQuery{Name: filterName},
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	filtered := selectableData1.Filter()

	data1 := filtered.Sort().Paginate()

	total1 := len(data1.GenericDataList)
	pods1 := p.fromCells(data1.GenericDataList)
	return &PodsResp{
		Total: total1,
		Items: pods1,
	}, nil
}
